import { login, logout, getInfo  } from '@/api/login'
import { getAccessToken, setAccessToken, removeAccessToken ,getRefreshToken ,setRefreshToken,removeRefreshToken } from '@/utils/auth'

const user = {
  state: {
		//access_token
    access_token: getAccessToken(),
		refresh_token:getRefreshToken(),
    name: '',
    avatar: '',
    roles: []
  },

  mutations: {
    SET_ACCESS_TOKEN: (state, token) => {
      state.access_token = token
    },
		SET_REFRESH_TOKEN: (state, token) => {
		  state.refresh_token = token
		},
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const email = userInfo.email.trim()
      return new Promise((resolve, reject) => {
        login(email, userInfo.password).then(response => {
          const data = response.data
          setAccessToken(data.access_token)
          setRefreshToken(data.refresh_token)
          commit('SET_ACCESS_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    restToken({commit},newtoken){
      return new Promise(resolve => {
        setAccessToken(newtoken.access_token)
        setRefreshToken(newtoken.refresh_token)
        commit('SET_ACCESS_TOKEN', newtoken.access_token)
        commit('SET_REFRESH_TOKEN', newtoken.refresh_token)
        resolve()
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            console.log(data.roles)
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.nickname)
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_ACCESS_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_ROLES', [])
          removeAccessToken()
          removeRefreshToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_ACCESS_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        removeAccessToken()
        removeRefreshToken()
        resolve()
      })
    }
  }
}

export default user
